<template>
  <TreeSelect v-model="selectedValue"
              @change="handleChange"
              :props="{ label: 'sectionName' }"
              :data="treeData"/>
</template>
<script>

import TreeSelect from './TreeSelect.vue'
import api from "@/common/api.js";
import utils from "@/common/utils.js";

export default {
  name: 'SectionParentSelect',
  props: {
    courseId: {
      type: [String, Number],
      default: undefined
    },
    value: {
      type: [String, Number],
      default: undefined
    },
  },
  components: {
    TreeSelect
  },
  emits: ['input', 'change'],
  data() {
    return {
      selectedValue: undefined,
      treeOptions: {
        label: 'sectionName',
        children: 'children',
        isLeaf: (data) => {
          return !data.fileUrl
        }
      },
      treeData: [],
    }
  },
  mounted() {
    this.getTreeData();
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selectedValue = val
      }
    }
  },
  methods: {
    async getTreeData() {
      const {data} = await api.admin_getCourseSectionList({courseId: this.courseId});
      const list = data.data?.records?.filter(item => !item.fileUrl);      
      const root = {
        id: 0,
        sectionName: '所有章节',
        children: list
      }
      this.treeData = utils.buildTreeWithParentId(list, root);
    },
    handleChange(value) {      
      this.$emit('input', value)
      this.$emit('change', value)
    }
  }
}
</script>
